package me.zingon.web;

import me.zingon.common.Constant;
import me.zingon.model.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LoginFilter implements Filter {

	List<String> ignoreList = new ArrayList<>();

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest) request;
		HttpServletResponse resp= (HttpServletResponse) response;
		HttpSession session=req.getSession(true);
		String uri=req.getRequestURI();
		User u= (User) session.getAttribute(Constant.SESSION_USER);
		if(isIgnored(uri)){
			chain.doFilter(request,response);
			return;
		}
		if(u==null) {
			resp.sendRedirect(req.getContextPath()+"/user.pj");
			return;
		}
		chain.doFilter(request,response);
	}

	public void init(FilterConfig config) throws ServletException {
		ignoreList= Arrays.asList(config.getInitParameter("ignoreList").split(","));
	}

	private boolean isIgnored(String uri) {
		for (String ignore : ignoreList) {
			if (uri.contains(ignore)) {
				return true;
			}
		}
		return false;
	}

}
